package cn.tpshion.config.service.impl;

import cn.tpshion.config.common.BusinessException;
import cn.tpshion.config.common.ErrorCode;
import cn.tpshion.config.common.JwtUtil;
import cn.tpshion.config.domain.entity.AuthInfo;
import cn.tpshion.config.service.AuthService;
import cn.tpshion.config.support.AuthProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class InMemoryAuthServiceImpl implements AuthService {

    @Autowired
    private AuthProperties authProperties;

    @Override
    public String checkUser(AuthInfo authInfo) {
        log.info("authProperties:{}",authProperties);
        log.info("authInfo:{}",authInfo);
        if(!authProperties.getUsername().equals(authInfo.getUsername())){
            throw new BusinessException(ErrorCode.TOKEN_ERROR);
        }
        if(!authProperties.getPassword().equals(authInfo.getPassword())){
            throw new BusinessException(ErrorCode.TOKEN_ERROR);
        }
        return JwtUtil.createToken(authInfo);
    }

    @Override
    public String checkCode(String secretkey) {
        log.info("authProperties:{}",authProperties);
        log.info("authInfo:{}",secretkey);
        if(!StringUtils.hasText(authProperties.getSecretkey())){
            log.error("认知失败，secretkey授权码未配置");
            throw new BusinessException(ErrorCode.TOKEN_ERROR);
        }
        if(!authProperties.getSecretkey().equals(secretkey)){
            throw new BusinessException(ErrorCode.TOKEN_ERROR);
        }
        AuthInfo authInfo = new AuthInfo();
        authInfo.setUsername("admin");
        authInfo.setPassword(secretkey);
        return JwtUtil.createToken(authInfo);
    }
}
